const path = require('path')
const webpack = require('webpack')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const HappyPack = require('happypack')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')

// 构造出一个共享进程池，在进程池中包含4个子进程
const happyThreadPool = HappyPack.ThreadPool({
  size: 4
})

module.exports = {
  entry: './src/main.js',
  output: {
    filename: '[name].[hash].js',
    path: path.resolve(__dirname, 'dist'),
    chunkFilename: '[id].[chunkhash].js'
  },
  optimization: {
    splitChunks: {
      cacheGroups: {
        styles: {
          name: 'styles',
          test: /\.less|css$/,
          chunks: 'all',
          enforce: true
        }
      }
    }
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        // 排除node_modules下的js
        exclude: /node_modules/,
        // 将对.js文件的处理转交给id为babel的happypack实例
        use: ['happypack/loader?id=babel']
      },
      {
        test: /\.vue$/,
        use: 'vue-loader'
      },
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader']
      },
      {
        test: /\.less$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader', 'less-loader']
      },
      // webpack 5 对于图片处理需要用 asset module
      {
        test: /\.png$/,
        type: 'asset/resource'
      }
      // {
      //   test: /\.png$/,
      //   use: {
      //     loader: 'url-loader',
      //     options: {
      //       limit: 10 * 1024
      //     }
      //   }
      // }
    ]
  },
  plugins: [
    new VueLoaderPlugin(), // vue文件
    new webpack.ProgressPlugin(), // webpack 内置
    new webpack.DefinePlugin({
      BASE_URL: JSON.stringify('/')
    }),
    new HappyPack({
      // 用唯一的标识符 id 来代表当前的 HappyPack 是用来处理一类特定的文件
      id: 'babel',
      loaders: ['babel-loader?cacheDirectory=true'],
      // 使用共享进程池中的自进程去处理任务
      threadPool: happyThreadPool,
      // 是否允许happypack输出日志，默认true
      verbose: true
    }),
    new MiniCssExtractPlugin({
      filename: '[name].css',
      chunkFilename: '[id].css'
    })
  ]
}
